/*
* Copyright 2018 Shanxi Lu'an Taihang Laihui Net Tech co.,LTD.
*/
package com.laihuichuxing.bus.provider;

import com.alibaba.dubbo.config.annotation.Service;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.laihuichuxing.bus.dao.BusOrderDao;
import com.laihuichuxing.bus.dao.OrderPassengerDao;
import com.laihuichuxing.common.util.DateUtil;
import com.laihuichuxing.common.util.JsonUtil;
import com.laihuichuxing.config.ResponseCode;
import com.laihuichuxing.order.bus.api.BusOrderServerApi;
import com.laihuichuxing.order.bus.api.OrderPassengerServerApi;
import com.laihuichuxing.order.bus.entity.BusOrderEntity;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.*;

/**
 * Description: 大巴订单服务api
 *
 * @author: Qinxuefeng
 * @since: 1.0
 * Create Date Time: 2018/12/11 14:10
 * Update Date Time:
 */
@Service(version = "1.0.0",interfaceClass = BusOrderServerApi.class)
public class BusServerProvider implements BusOrderServerApi,OrderPassengerServerApi{
    @Autowired
    private BusOrderDao busOrderDao;
    @Autowired
    private OrderPassengerDao orderPassengerDao;
    @Override
    public Map<String, Object> pottingOrder(String token, Map<String, Object> resultMap, String userId) {
        List<Map<String,Object>> olist = busOrderDao.getPassengerByToken(token,null,"1");
        Map<String, Object> map = Maps.newHashMap();
        if(!olist.isEmpty()){
            map.put("orderNumber",olist.get(0).get("order_number"));
        }else{
            map.put("orderNumber","");
        }
        //大巴行程信息
        Map<String,Object> busInfo = new HashMap<>();
        BusOrderEntity bus = busOrderDao.findRecentOrder(userId);
        if(bus != null){
            String timeStr =  bus.getDptDateTime();
            timeStr = timeStr.substring(0,timeStr.length()-2);
            busInfo.put("departure",bus.getDeparture());
            busInfo.put("destination",bus.getDestination());
            busInfo.put("orderNumber",bus.getOrderNumber());
            busInfo.put("dptDateTime",timeStr);
        }
        resultMap.put("bus", map);
        resultMap.put("busInfo",busInfo);
        return resultMap;
    }

    @Override
    public Map<String,String> findReOrder(String s) {
        return getValue(busOrderDao.findReOrder(s));
    }

    @Override
    public Map<String, Object> deleteOrder(String token, String orderNumber) {
        List<Map<String,Object>> olist = busOrderDao.getPassengerByToken(token, orderNumber, null);
        if (!olist.isEmpty()) {
            if ("1".equals(olist.get(0).get("status"))) {
                int count =busOrderDao.updateStatus(orderNumber,9);
                if (count == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return JsonUtil.getJson(ResponseCode.FAIL, "操作失败", olist);
                }
            } else if ("6".equals(olist.get(0).get("status"))) {
                int count =busOrderDao.updateStatus(orderNumber,8);
                if (count == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return JsonUtil.getJson(ResponseCode.FAIL, "操作失败", olist);
                }
            } else {
                return JsonUtil.getJson(ResponseCode.SUCCESS, "此条已删除",olist);
            }
        } else {
            return JsonUtil.getJson(ResponseCode.SUCCESS, "此条已删除", olist);
        }
        return JsonUtil.getJson(ResponseCode.SUCCESS, "操作成功", olist);
    }

    @Override
    public Map<String, Object> updateOrderAndStream(String orderNumber, String type, Map<String, Object> map,
                                                    Object userId, int num, String tcOrderId) {
        int count = busOrderDao.updateTcOrderId(tcOrderId,orderNumber);
        if (count == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return JsonUtil.getJson(ResponseCode.FAIL, "操作失败", map);
        }
        BigDecimal all = new BigDecimal(map.get("TicketPrice").toString()).multiply(new BigDecimal(num)).add(new BigDecimal(map.get("ServicePrice").toString()).multiply(new BigDecimal(num))).setScale(2);
        StringBuilder str = new StringBuilder();
        str.append("insert into jhcx_bus_stream (order_serial_id,order_number,ticket_price,cash_pay_type,cash_user_id,service_amount,all_price," +
                "create_time,is_enable,ticket_num)");
        str.append(" values ( '" + tcOrderId + "','" + orderNumber + "','" + map.get("TicketPrice") + "','" + type + "','" + userId + "','" + map.get("ServicePrice") + "'," +
                "'" + all + "','" + DateUtil.getCurrentTime() + "','1','" + num + "')");
        busOrderDao.createBySql(str.toString());
        StringBuilder str2 = new StringBuilder();
        String uuid= UUID.randomUUID().toString().replace("-", "");
        str2.append("insert into jhcx_push (push_id,user_id,driver_trade_no,passenger_trade_no,title,content,type,push_time,is_view," +
                "push_type)");
        str2.append(" values ( '"+uuid+"','"+userId+"','"+tcOrderId +"','"+orderNumber + "','汽车票支付消息','你已支付了"+map.get("DptDateTime")
                +map.get("Departure")+"到"+map.get("Destination")+"汽车票"+"','1','"+DateUtil.getCurrentTime() +"','1','4')");
        busOrderDao.createBySql(str2.toString());
        Map<String,Object> param = Maps.newHashMap();
        param.put("tcOrderId", tcOrderId);
        return JsonUtil.getJson(ResponseCode.SUCCESS, "请求成功", param);
    }

    @Override
    public void createOrder(Map<String, Object> user, Map<String, Object> map, BigDecimal bigDecimal, String uuid, String sendSms,
                                           String canRefund, String refundType, String refundBeforeDepart,
                                           String hasSelfInsurance, String exData, int num, String coachNo)throws Exception {
        try {
            StringBuilder oString = new StringBuilder();
            oString.append("INSERT INTO jhcx_bus_order (order_number,departure,destination,dpt_station,arr_station," +
                    "dpt_date_time,ticket_price,service_price,schedule_no,contact_name,contact_mobile_no,contact_id_card," +
                    "ex_data,send_sms,has_self_insurance,self_insurance_amount,user_id,create_time,coach_type,can_refund,refund_type,num,refund_before_depart,coach_no) values ");
            oString.append("('" + uuid + "','" + map.get("departure") + "','" + map.get("destination") + "','" + map.get("dptStation") + "','" + map.get("arrStation")
                    + "','" + map.get("dptDateTime") + "','" + bigDecimal + "','" + map.get("servicePrice") + "','"
                    + map.get("scheduleNo") + "','" + map.get("contactName") + "','" + map.get("contactMobileNo") + "','"
                    + map.get("contactIdCard") + "','" + exData + "','" + sendSms + "','" + hasSelfInsurance + "','"
                    + map.get("selfInsuranceAmount") + "','" + MapUtils.getString(user, "userId") + "','" + DateUtil.getCurrentTime() + "','" + map.get("coachType")
                    + "','" + canRefund + "','" + refundType +"','" + num + "','" + refundBeforeDepart + "','"+coachNo+"')");
            int count=busOrderDao.createBySql(oString.toString());
            if (count == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new Exception("操作失败");
            }
        }catch (Exception e){
            throw new Exception("操作失败");
        }
    }

    @Override
    public List<Map<String, Object>> getOrderList(String token, String orderNumber, String status, String pageNo, String pageSize) {
        String start = "", end = "";
        if (!Strings.isNullOrEmpty(pageNo)) {

            start = String.valueOf((Integer.valueOf(pageNo) - 1) * Integer.valueOf(pageSize));
            end = String.valueOf(Integer.valueOf(pageNo) * Integer.valueOf(pageSize));
        }
        List<Map<String,Object>> olist = busOrderDao.getPassengerByTokenLimit(token, orderNumber, status, start, end);
        olist.forEach(list -> {
            list.put("passengerInfo", orderPassengerDao.selectList(list.get("orderNumber").toString()));
        });
        return olist;
    }

    @Override
    public Map<String, Object> getOrderListz(String orderNumber) {
        Map<String, Object> olist = busOrderDao.getOrderByOderNumber(orderNumber);
        List<Map<String, Object>> list = orderPassengerDao.selectOrderList(olist.get("OrderNumber").toString());
        List<Map<String, Object>> listNew = new ArrayList<>();
        list.forEach(lists -> {
            lists.put("IsChild", "0".equals(lists.get("IsChild")) ? false : true);
            listNew.add(sortMapByKey(lists, true));
        });
        olist.put("num", list.size());
        //Object[] o = list.toArray();
        olist.put("PassengerInfo", listNew);
        return olist;
    }

    @Override
    public List<Map<String, Object>> getPassengerByToken(String s, String s1, String s2) {
        return busOrderDao.getPassengerByToken(s,s1,s2);
    }

    @Override
    public int updateStream(String orderNumber, String status) {
        return busOrderDao.updateSteamStatus(orderNumber,status);
    }

    /**
     * 使用 Map 按 Key 进行排序
     *
     * @param oriMap 排序 Map 集合
     * @param isRise 是否按照升序排序
     */
    private static Map<String, Object> sortMapByKey(Map<String, Object> oriMap, final boolean isRise) {
        if (oriMap == null || oriMap.isEmpty()) {
            return null;
        }
        Map<String, Object> sortMap = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                if (isRise) {
                    // 升序排序
                    return o1.compareTo(o2);
                } else {
                    // 降序排序
                    return o2.compareTo(o1);
                }
            }
        });
        sortMap.putAll(oriMap);
        return sortMap;
    }
    private Map<String ,String > getValue(Map<String, Object> map) {
        Map<String ,String > maps=Maps.newHashMap();
        for(String str:map.keySet()){
            maps.put(str,map.get(str)==null?"":map.get(str).toString());
        }
        return maps;
    }

    @Override
    public void createPassger(List<Map<String, Object>> pList, String uuid)throws Exception {
        try {
            StringBuilder rString = new StringBuilder();
            rString.append("INSERT INTO jhcx_bus_order_passenger (order_number,name,id_type,mobile_no" +
                    ",is_child,id_card) values");
            pList.forEach(passenger -> rString.append("('" + uuid + "','" + passenger.get("name") + "','" + "1"
                    + "','" + passenger.get("mobileNo") + "','" + passenger.get("isChild") + "','" + passenger.get("idCard") + "'),"));
            int count =busOrderDao.createBySql(rString.deleteCharAt(rString.length() - 1).toString());
            if (count == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new Exception("操作失败");
            }
        }catch (Exception e){
            throw new Exception("操作失败");
        }
    }

    @Override
    public List<Map<String, Object>> selectList(String s) {
        return orderPassengerDao.selectList(s);
    }
}
